package org.docshare.http;

import android.content.Context;
import android.renderscript.Type;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;

import cz.msebera.android.httpclient.Header;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import org.docshare.helper.FileHelper;
import org.docshare.helper.TextTool;


/**
 * Created by Administrator on 2016/5/15.
 */
public class DataServer {
    private static final String TAG = "DataServer";
    private static final String  SERVER_URL  = "http://www.docshare.org/app/server.php";
    //private static final String  SERVER_URL  = "http://192.168.1.102/app/server.php";
    
    static  DataServer ins = null;
    String sid = null;
    String uid = null;
    YangResponse resp;

    public static  DataServer getIns(Context ctx){
        if(ins ==  null){
            ins = new DataServer(ctx);
        }
        return ins;
    }
    

    public DataServer(Context ctx) {
    	//client.setMaxRetriesAndTimeout(1, 10000);
    	client.setMaxConnections(1);
    	client.setConnectTimeout(10000);
    	client.setResponseTimeout(300000);
    	PersistentCookieStore myCookieStore = new PersistentCookieStore(ctx);    
    	client.setCookieStore(myCookieStore);
	}

	AsyncHttpClient client = new AsyncHttpClient();

    /**
     * 登陆服务器
     * @param uid
     * @param pwd
     * @param resp
     */
    public void login(String uid, String pwd,final YangResponse resp){
        if(sid !=null){
            resp.onResult(true,"已登录");
            return;
        }
        
        RequestParams param = new RequestParams();
        param.add("action","login");
        param.add("uid",uid);
        param.add("pwd",pwd);
        this.uid = uid;
        client.get(SERVER_URL,param, new MyCallBack(resp) {

            @Override
            public void onData(boolean succ, String data) {
            	try{
	                LoginResp r = JSON.parseObject(data,LoginResp.class);
	                JSONObject obj = JSON.parseObject(data);
	                DataServer.this.sid = r.sid;
	                DataServer.this.uid = r.uid;
	                resp.onResult(r.result.equals("ok"),r.msg);
            	}catch(Exception e){
            		e.printStackTrace();
            		resp.onResult(false, "网络通讯出现错误");
            	}
            }
        });
    }

    /**
     * 获取书籍列表
     * @param resp
     */
    public void fav(final YangResponse resp){
        RequestParams param = new RequestParams();
        param.add("action","fav");
        param.add("sid",sid);
        param.add("uid",uid);
        client.get(SERVER_URL, param, new MyCallBack(resp) {
            @Override
            public void onData(boolean succ, String s) {
                Log.i(TAG, "fav onSuccess: "+s);
                try{
	                s = s.replace("\\r\\n","");
	                JSONObject obj = JSON.parseObject(s);
	                String r = obj.getString("result");
	                JSONArray data = obj.getJSONArray("data");
	
	                try {
	                    //Map<String,Object> map = C.objectToMap(r.data);
	                    resp.onResult(r.equals("ok"),data);
	                } catch (Exception e) {
	                    e.printStackTrace();
	                }
                }catch(Exception e){

            		e.printStackTrace();
            		resp.onResult(false, "网络通讯出现错误");
                }

            }
        });
    }

    /**
     * 远程提供界面
     * @param resp
     */
    public void view(String url,String id,Context ctx,final YangResponse resp){
    	url = url.replace("view://", "");
    	try {
    		String asset_file  = id == null? "view/"+url+".json": "view/"+url+"_"+id+".json";
    		
			InputStream is = ctx.getAssets().open(asset_file);
			String s = FileHelper.readAll(is);
			JSONObject obj = JSON.parseObject(s);
			resp.onResult(true, obj);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			//e1.printStackTrace();
			Log.d(TAG,"not found in assets read from web"+url);
		}
    	
    	
        RequestParams param = new RequestParams();
        String type = url.replace("view://","");
        
        if(id!=null){
        	param.add("id", id);
        }
            
        param.add("action","view");
        param.add("type",type);
        param.add("uid",uid);
        param.add("sid",sid);
        Log.d("TAG","read data from "+SERVER_URL+"?"+param.toString());
        client.get(SERVER_URL, param, new MyCallBack(resp) {
            @Override
            public void onData(boolean succ, String s) {
            	try {
            		Log.i(TAG, "view onSuccess: "+s);
                    s = s.replace("\\r\\n","");
                    JSONObject obj = JSON.parseObject(s);
                    if(obj == null){
                    	Log.e(TAG,"parse object error: "+s);
                    	return;
                    }
                    String r = obj.getString("result");
                    
                    Object data = obj.get("data");
                    
                    resp.onResult(r.equals("ok"),data);
				} catch (Exception e) {
            		e.printStackTrace();
            		resp.onResult(false, "网络通讯出现错误");
				}
                

            }
        });
    }
    
    public void read(String url,final YangResponse resp){
    	//try to read from local db
    	
    	
    	
        RequestParams param = new RequestParams();
    	client.get(url, param,new MyCallBack(resp) {
			
			@Override
			public void onData(boolean succ, String data) {
				try{
					Log.i(TAG,succ+":"+data);
					resp.onResult(succ, data);
				}catch(Exception e){
            		e.printStackTrace();
            		resp.onResult(false, "网络通讯出现错误");
				}
			}
		});
    }
    
    public void dir(int bookid,final YangResponse resp){
        RequestParams param = new RequestParams();
        param.add("action","dir");
        param.add("bookid",bookid+"");
        client.get(SERVER_URL, param, new MyCallBack(resp) {
            @Override
            public void onData(boolean succ, String s) {
            	try{
	                Log.i(TAG, "dir onSuccess: "+s);
	                JSONObject obj = JSON.parseObject(s);
	                String r = obj.getString("result");
	                JSONArray data = obj.getJSONArray("data");
	                resp.onResult(r.equals("ok"),data);
            	}catch(Exception e){
            		e.printStackTrace();
            		resp.onResult(false, "网络通讯出现错误");
            	}
            }
        });
    }

    public boolean isLogin(){
        return sid != null;
    }

    /**
     * 为了简化代码而自己封装的回调子类，对解码失败和网络失败采用同样处理
     */
    abstract class MyCallBack extends   AsyncHttpResponseHandler{
        private final YangResponse resp;

        public MyCallBack(YangResponse resp){
            this.resp = resp;
            
        }
        
        public abstract void onData(boolean succ,String data);
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String s = null;
            try {
                s = new String(responseBody,"utf-8");
                if(s.contains("gbk") || s.contains("gb2312")){
                	s = new String(responseBody,"gbk");
                }
                
                Log.i(TAG, "onSuccess: "+s);
                onData(true,s);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                resp.onResult(false,"网页解码错误");
                Log.e(TAG, "onSuccess: decode page error");
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            Log.e(TAG, "onFailure: network error" + error.getMessage());
            resp.onResult(false,"网络错误");
            Log.e(TAG, "onFailure: network fail");
        }
    }

}

class LoginResp {
    public String result;
    public String uid;
    public String sid;
    public String msg;
}
class FavBook{
    public int fid;
    public int bookid;
    public String bookname;
    public Date viewtm;
    public String lastreadtitle;
    public int lastscid;
    public int iszhu;
    public String author;
    public String img;
    public int last_capid;
    public String last_captitle;

}
class FavResp{
    public String result;
    public List<FavBook> data;
}
